package com.cmict.data.system.api.permission;

import com.cmict.data.framework.common.pojo.CommonResult;
import com.cmict.data.system.api.permission.dto.MenuDTO;
import com.cmict.data.system.convert.permission.MenuConvert;
import com.cmict.data.system.enums.ApiConstants;
import com.cmict.data.system.mq.producer.permission.MenuProducer;
import com.cmict.data.system.service.permission.MenuService;
import com.cmict.data.system.service.permission.PermissionService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * 权限 API 实现类
 *
 * @author awesome
 */
@RestController // 提供 RESTful API 接口，给 Feign 调用
@DubboService(version = ApiConstants.VERSION) // 提供 Dubbo RPC 接口，给 Dubbo Consumer 调用
@Validated
public class MenuApiImpl implements MenuApi {

    @Resource
    private MenuService menuService;

    @Resource
    private PermissionService permissionService;

    @Resource
    private MenuProducer menuProducer;

    /**
     * 表单发布删除菜单
     *
     * @param menuId 菜单编号
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public CommonResult<Boolean> deleteMenuForm(Long menuId) {
        // 校验删除的菜单是否存在
        if (menuService.selectById(menuId) != null) {
            // 标记删除
            menuService.deleteById(menuId);
            // 删除授予给角色的权限
            permissionService.processMenuDeleted(menuId);
            // 发送刷新消息. 注意，需要事务提交后，在进行发送刷新消息。不然 db 还未提交，结果缓存先刷新了
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {

                @Override
                public void afterCommit() {
                    menuProducer.sendMenuRefreshMessage();
                }

            });
            return CommonResult.success(true);
        }
        return CommonResult.success(false);
    }

    @Override
    public CommonResult<List<MenuDTO>> getMenus() {
        List<MenuDTO> menuDTOS = MenuConvert.INSTANCE.convertList07(menuService.getMenus());
        return CommonResult.success(menuDTOS);
    }

    @Override
    public CommonResult<MenuDTO> getFromId(Long menuId) {
        MenuDTO menuDTO = MenuConvert.INSTANCE.convertList08(menuService.getMenu(menuId));
        return CommonResult.success(menuDTO);
    }

}
